<?php
    //
    //  Created by Chagan Anton on 29.07.12.
    //  Copyright Chagan Anton 2012. All rights reserved.
    //
/**
 * This is the model class for table "users".
 */
class Admins extends CActiveRecord
{
	const ROLE_USER = 'user';
	const ROLE_ADMIN = 'admin';
	const ROLE_ROOT = 'root';
	
	const STATE_ACTIVE = 1;
	const STATE_DISABLED = 2;
	
	public $prevRole = null;
	/**
	 * The followings are the available columns in table 'users':
	 * @var integer $u_id
	 * @var string $u_name
	 * @var string $u_email
	 * @var string $u_pass
	 * @var integer $u_state
	 * @var string $u_role
	 */

	/**
	 * Returns the static model of the specified AR class.
	 * @return Users the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'admins';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('u_name, u_email, u_pass, u_state', 'required'),
			array('u_email', 'unique'),
			array('u_role', 'safe'),
			array('u_state', 'numerical', 'integerOnly'=>true),
			array('u_name, u_email, u_pass', 'length', 'max'=>255),
			array('u_email', 'email'),
			array('u_pass', 'length', 'min'=>5),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('u_id, u_name, u_email, u_pass, u_state, u_role', 'safe', 'on'=>'search'),
		);
	}
	
	public function beforeSave() {
		parent::beforeSave();
		$this->u_pass = md5($this->u_pass);
		/*
		 * Если пользователь не имеет права изменять роль, то мы должны
		 * установить роль по-умолчанию (user)
		 */
		if (!Yii::app()->user->checkAccess('changeRole')) {
			if ($this->isNewRecord) {
				//ставим роль по-умолчанию user
				$this->u_role = Admins::ROLE_USER;
			}
		}
		return true;
	}
	
	public function afterSave() {
		parent::afterSave();
		//связываем нового пользователя с ролью
		$auth=Yii::app()->authManager;
		//предварительно удаляем старую связь
		$auth->revoke($this->prevRole, $this->u_id);
		$auth->assign($this->u_role, $this->u_id);
		$auth->save();
		return true;
	}
	
	public function beforeDelete() {
		parent::beforeDelete();
		//убираем связь удаленного пользователя с ролью
		$auth=Yii::app()->authManager;
		$auth->revoke($this->u_role, $this->u_id);
		$auth->save();
		return true;
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'u_id' => '#',
			'u_name' => 'User Name',
			'u_email' => 'User Email',
			'u_pass' => 'User Password',
			'u_state' => 'User State',
			'u_role' => 'User Role',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('u_id',$this->u_id);

		$criteria->compare('u_name',$this->u_name,true);

		$criteria->compare('u_email',$this->u_email,true);

		$criteria->compare('u_pass',$this->u_pass,true);

		$criteria->compare('u_state',$this->u_state);

		$criteria->compare('u_role',$this->u_role,true);

		return new CActiveDataProvider(get_class($this), array(
			'criteria'=>$criteria,
		));
	}
}